﻿/// <reference path="../jquery-1.6.2-vsdoc.js" />

/***** Variables *****/
//Current edit row
var editRowId = 0;
//Pre-edit row values
var oldValue = {};
//Id for new row
var newRowId = -1;
//Flag to tell if adding new row in progress
var rowAdding = false;

/***** Master helpers *****/
function mouseEnter() {
    $(this).css('background', '#fff').css('color', '#000');
}

function mouseLeave() {
    $(this).css('background', '#000').css('color', '#fff');
}

//Start up
$(document).ready(function () {
    //Button effect
    $('.slideButton').hover(mouseEnter, mouseLeave);
    // Click handlers
    $('.gridButtonRight').click(gridButtonRight_OnClick);
    $('.gridButtonLeft').click(gridButtonLeft_OnClick);
    $('#btnAddItem').click(btnAddItem_OnClick);
    // Enhance textarea
    $('#subTable textarea').elastic();
});

function gridButtonLeft_OnClick(evt) {
    var rowId = getRowId($(this));
    if ($(this).html() == 'Lưu') {
        //Disable edit
        disableEditRow(rowId);
        editRowId = 0;
        //Exit adding mode
        rowAdding = false;
        //Callback and save data
        showLoading();
        //Build json params
        var editRow = getRowById(rowId)
        var params = {};
        params.id = rowId;
        params.text = editRow.find('#item_Text').val();
        params.start = editRow.find('#item_Start').val();
        params.end = editRow.find('#item_End').val();
        $.ajax({
            type: 'POST',
            url: 'Slide/InsertUpdate',
            data: $.toJSON(params),
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            success: function (resultObj) {
                //Parse the JSON result and process
                hideLoading(true, resultObj.message);
            },
            error: function (xml, textStatus, errorThrown) {
                //Show error
                hideLoading(false, 'ERROR: ' + xml.status + ' - ' + errorThrown);
            }
        });
    }
    else {
        //Alert on edit row still open
        if (editRowId !== 0) alert('Bạn cần phải lưu/hủy dòng đang chỉnh sửa trước.');
        else {
            //Enable row editing
            enableEditRow(rowId);
            editRowId = rowId;
            //Save pre-edit values
            saveOldRowValues(rowId);
        }
    }
}

function gridButtonRight_OnClick(evt) {
    var rowId = getRowId($(this));
    if ($(this).html() == 'Hủy') {
        //Adding mode
        if (rowAdding) {
            //Remove adding row
            deleteRow(rowId);
            //Exit adding mode
            rowAdding = false;
        }
        //Edit mode
        else {
            //Disable row editing
            disableEditRow(rowId);
            //Restore pre-edit values
            restoreOldRowValues(rowId);
        }
        //Exit editing mode
        editRowId = 0;
    }
    else {
        if (confirm('Bạn muốn xóa dòng này?')) {
            deleteRow(rowId);
            //Callback to delete data
            showLoading();
            var params = {};
            params.id = rowId;
            $.ajax({
                type: 'POST',
                url: 'Slide/Delete',
                data: $.toJSON(params),
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                success: function (resultObj) {
                    //Parse the JSON result and process
                    hideLoading(true, resultObj.message);
                },
                error: function (xml, textStatus, errorThrown) {
                    //Show error
                    hideLoading(false, 'ERROR: ' + xml.status + ' - ' + errorThrown);
                }
            });
        }
    }
}

function btnAddItem_OnClick(evt) {
    if (editRowId !== 0)
        alert('Bạn cần phải lưu/hủy dòng đang chỉnh sửa trước.');
    else {
        //Add row on top
        addRow(true);
        //Enter adding mode
        rowAdding = true;
    }
}

/****************** Helpers *********************/
//Get row Id by a row cell
function getRowId(cell) {
    return cell.parent().parent().find('input[type=hidden]').val();
}

//Get a row by its Id
function getRowById(rowId) {
    var row;
    $('#subTable tr').each(function () {
        if ($(this).find('input[type=hidden]').val() == rowId) {
            row = $(this);
            return false;
        }
    });
    return row;
}

function enableEditRow(rowId) {
    //Get edit row
    var editRow = getRowById(rowId);
    //Enable text fields
    editRow.find('.editable').each(function () {
        $(this).removeAttr('disabled');
    });

    //Rename buttons
    editRow.find('.gridButtonLeft').html('Lưu');
    editRow.find('.gridButtonRight').html('Hủy');
}

function disableEditRow(rowId) {
    //Get edit row
    var editRow = getRowById(rowId);

    //Disable text fields
    editRow.find('.editable').each(function () {
        $(this).attr('disabled', 'disabled');
    });

    //Rename buttons
    editRow.find('.gridButtonLeft').html('Sửa');
    editRow.find('.gridButtonRight').html('Xóa');
}

//Store the old values of a pre-edit row
function saveOldRowValues(rowId) {
    //Find row
    var editRow = getRowById(rowId);
    //Value fields counter
    var i = 0;
    //Loop row cells
    editRow.find('.editable').each(function () {
        oldValue[i] = $(this).val();
        i++;
    });
}

//Restore an edit row to pre-edit values
function restoreOldRowValues(rowId) {
    if (oldValue !== undefined && oldValue !== null) {
        //Find row
        var editRow = getRowById(rowId);
        //Value fields counter
        var i = 0;
        //Loop row cells
        editRow.find('.editable').each(function () {
            $(this).val(oldValue[i]);
            i++;
        });
    }
}

//Delete a table row
function deleteRow(rowId) {
    getRowById(rowId).remove();
}

//Build new row markup
function newRowHTML() {
    return '<tr valign="top">' +
        '<td>' +
            '<input id="newId" name="newId" type="hidden" value="' + newRowId + '">' +
            '<textarea class="subText editable" cols="20" id="item_Text" name="item_Text" rows="2">Dòng mới</textarea>' +
        '</td>' +
        '<td>' +
            '<input class="subTime editable" id="item_Start" name="item_Start" type="text" value="0">' +
        '</td>' +
        '<td>' +
            '<input class="subTime editable" id="item_End" name="item_End" type="text" value="0">' +
        '</td>' +
        '<td>' +
            '<div class="slideButton gridButtonLeft">Lưu</div>' +
        '</td>' +
        '<td>' +
            '<div class="slideButton gridButtonRight">Hủy</div>' +
        '</td>' +
    '</tr>';
}

//Add a table row
function addRow(addBottom) {
    if (addBottom) {
        //Find the next-to-last row, since last row is the Add button row
        $('#subTable tr:last-child').prev().after(newRowHTML());
    }
    else {
        //After the first row, since first row is the header row
        $('#subTable tr:first-child').after(newRowHTML());
    }

    //Assign edit row to this new row
    editRowId = newRowId;
    //Generate next new row Id
    newRowId--;

    //Attach JS for new row controls
    getRowById(editRowId).find('.gridButtonLeft').click(gridButtonLeft_OnClick).hover(mouseEnter, mouseLeave);
    getRowById(editRowId).find('.gridButtonRight').click(gridButtonRight_OnClick).hover(mouseEnter, mouseLeave);
    getRowById(editRowId).find('textarea').elastic();
}

function showLoading() {
    $('#subEditor').block({
        message: 'Xử lý thông tin...',
        css: {
            border: '1px solid #111',
            padding: '10px',
            fontFamily: 'Tahoma'
        },
        overlayCSS: {
            backgroundColor: '#FFF',
            opacity: 0.2
        }
    });
}

//Hide the loading panel with feedback message
function hideLoading(succeeded, msg) {
    //Succeeded operation
    if (succeeded) {
        $('#subEditor').block({
            message: msg,
            css: {
                border: '1px solid #111',
                padding: '10px',
                fontFamily: 'Tahoma',
                color: '#070',
            },
            overlayCSS: {
                backgroundColor: '#0F0',
                opacity: 0.1
            }
        });
        //Hide the message 
        setTimeout(function () {
            $('#subEditor').unblock();
        }, 1000);
    }
    //Failed operation
    else {
        $('#subEditor').block({
            message: msg,
            css: {
                border: '1px solid #111',
                padding: '10px',
                fontFamily: 'Tahoma',
                color: '#900'
            },
            overlayCSS: {
                backgroundColor: '#F00',
                opacity: 0.1
            }
        });
        //Hide the message 
        setTimeout(function () {
            $('#subEditor').unblock();
        }, 5000);
    }
}